import routerMap, { routerMapKeyList } from '@/router/routerMap'
import { useEffect } from 'react'
import {
  BrowserRouter,
  Navigate,
  NavigateFunction,
  Route,
  Routes,
  useNavigate,
} from 'react-router-dom'
import LocalStorageKey from './constant/LocalStorageKey'
import IMenuVO from './model/vo/menu/IMenuVO'
import noLoginList, { noLoginPathList } from './router/noLoginList'
import { useAppDispatch, useAppSelector } from './store'
import { setCurrentRouter } from './store/user/userSlice'

export default function App() {
  const userMenuList = useAppSelector(
    (state) => state.user.userMenuList
  ).filter((item) => !item.linkFlag && item.router)

  return (
    <BrowserRouter>
      <Routes>
        {/* 不用登录就可以访问的路由 ↓ */}
        {noLoginList.map((item, index) => (
          <Route
            key={index}
            path={item.path}
            element={
              <LoadElement title={item.title} elementTemp={item.elementTemp} />
            }
          ></Route>
        ))}
        {/* 不用登录就可以访问的路由 ↑ */}

        {/* 需要登录才可以访问的路由 ↓ */}
        <Route
          path="/admin"
          element={<LoadElement title="跳转中" elementTemp="admin" />}
        >
          {userMenuList.map((item) => (
            <Route
              key={item.id}
              path={item.path}
              element={
                <LoadElement
                  title={item.name}
                  elementTemp={item.router}
                  menuInfo={item}
                />
              }
            ></Route>
          ))}
        </Route>
        <Route
          path="*"
          // 备注：这里不需要设置 title = '404'，exception404 里面进行单独设置
          element={<LoadElement elementTemp="exception404" />}
        ></Route>
        {/* 需要登录才可以访问的路由 ↑ */}
      </Routes>
    </BrowserRouter>
  )
}

let AppNav: NavigateFunction
export function getAppNav() {
  return AppNav
}

interface ILoadElement {
  title?: string
  elementTemp: string
  menuInfo?: IMenuVO // 菜单信息
}

// 加载 element
function LoadElement(props: ILoadElement) {
  AppNav = useNavigate()

  if (props.title) {
    document.title = props.title // 修改标题
  }

  const jwt = localStorage.getItem(LocalStorageKey.JWT)

  const nologinPathFlag = noLoginPathList.includes(window.location.pathname) // 是否是：不登录就可以访问的路径

  const appDispatch = useAppDispatch()

  useEffect(() => {
    appDispatch(
      setCurrentRouter(props.menuInfo?.id ? props.menuInfo : ({} as IMenuVO)) // 如果不存在 menuInfo的，需要设置为 {}
    ) // 设置当前路由信息
  }, [props.elementTemp])

  if (!jwt && !nologinPathFlag) {
    return <Navigate to="/login" />
  }

  if (routerMapKeyList.includes(props.elementTemp)) {
    const Element = routerMap[props.elementTemp].elementTemp
    return <Element />
  }

  return null
}
